# 定义当前自子应用类的公共方法和库
import re

from django.contrib.auth.backends import ModelBackend
from .models import Users


# 添加自定义字段，重写jwt响应方法
def jwt_response_payload_handler(token, user=None, request=None):
    """

    :param token:生成token值
    :param user: 当前登陆用户【当前用户和注册用户传递过来的】
    :param request: 当前请求对象
    :return:
    """
    return {
        "token": token,
        "user_di": user.id,
        "username": user.username
    }


def get_user_by_account(account):
    """
    判断用户手机还是用户名
    :param account:
    :return:
    """
    try:
        if re.match('^1[3-9]\d{9}$', account):
            # 帐号为手机号
            user = Users.objects.get(mobile=account)
        else:
            # 帐号为用户名
            user = Users.objects.get(username=account)
    except Users.DoesNotExist:
        return None
    else:
        return user


class UsernameAuthModelBcakend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        """

        :param request: 本次请求对象
        :param username: 用户认证的账号
        :param password: 用户认证密码
        :param kwargs:
        :return:
        """
        user = get_user_by_account(username)
        # if user is not None and user.check_password(password):
        if user is not None and user.check_password(password):
            return user


from itsdangerous import TimedJSONWebSignatureSerializer as serializer, BadData
from django.conf import settings
from . import constants


def generate_save_user_token_url(user):
    """
    定义生成用户验证url并加密
    :param user: 当前用户对象
    :return: 返回一个url地址并携带授权令牌
    """
    # 创建itsdangerous 并添加时间戳和django秘钥
    Serializer = serializer(settings.SECRET_KEY, constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    # 对需要的用户信息保存
    data = {"user_id": user.id, "email": user.email}
    # 进行加密，返回bytes类型
    # URL安全序列化¶
    token = Serializer.dumps(data)
    # 返回bytes数据
    token = token.decode()

    # 拼接url地址
    verify_url = settings.VERIFY_EMAIL_HTML + '?token=' + token
    return verify_url


def check_verif_email_token(token):
    """

    :param token:用户user_id,user.email
    :return:
    """
    # 创建itsdangerous 并添加时间戳和django秘钥
    Serializer = serializer(settings.SECRET_KEY, constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    # 解密
    try:
        data = Serializer.loads(token)
        return data["user_id"]
    except BadData:
        return None
